package com.oceansoft.mobile.weixin.task;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.common.dao.CommonDaoImpl;
import com.oceansoft.mobile.weixin.service.WechatServiceImpl;
import com.oceansoft.mobile.weixin.util.DateUtil;
import com.oceansoft.mobile.weixin.util.WeixinUtil;

/**
 * Created by BEN on 2016/4/8.
 */
@Component
public class SummaryProcessor {

    @Resource
    private CommonDaoImpl dao;

    @Resource
    private WechatServiceImpl wechatService;

    public void test() {

        String start = "2016-04-20";
        String end = "2016-04-24";
        SimpleDateFormat dd = new SimpleDateFormat(DateUtil.PATTERN_DATE);
        try {
            Date d1 = dd.parse(start);
            Date d2 = dd.parse(end);
            GregorianCalendar gc = new GregorianCalendar();
            gc.setTime(d1);
            do {
                //统计
                String s = dd.format(gc.getTime());
                System.out.println(s);
                gc.add(5, 1); //增加一天
                d1 = gc.getTime();
                process(s);
            } while (!d1.after(d2));//判断是否还能运行

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    public void process() {
        System.out.println("SummaryProcessor任务开始运行");
        String yedate = DateUtil.date2String(DateUtil.getYesterdayDate(), DateUtil.PATTERN_DATE);
        String access_token = wechatService.getAccessTokenByopenId("gh_b6af115f3e1a");
        if (!access_token.equals("") && access_token != null) {


            this.deleteUserSummary(yedate);
            this.deleteUserCumulate(yedate);
            //保存增量数据
            this.saveUserCumulate(access_token, yedate, yedate);
            //保存汇总数据
            this.saveUserSummary(access_token, yedate, yedate);
        } else {
            System.out.println("SummaryProcessor运行异常access_token为空");
        }
        //统计昨天的访问数据
        rbtj(yedate);
        System.out.println("SummaryProcessor任务结束运行");
    }
    
    private  String rbtj(String rq1) {
    	
    	try{
    	String cjrewmsql = " update t_api_access_log t set t.url='https://wjw.szgaj.cn/szgawx/micro/redirect/0',source='ewm_crj' "+
    			" where t.url like 'https://wjw.szgaj.cn/szgawx/micro/redirect/45%' and source='crj' " +
    			" and  t.logdate = '"+rq1+"'";
    	dao.update(cjrewmsql);
    	}catch(Exception e)
    	{
    		e.printStackTrace();
    	}
		// 开始统计数据
		// 1.获取配置文件
    	SimpleDateFormat dd=new SimpleDateFormat("yyyy-MM-dd"); 
		String sql = "select * from t_url_mark ";
		List<Map<String, Object>> list = dao.loadMapList(sql);
		try {
			Date d1 = dd.parse(rq1);
			GregorianCalendar gc=new GregorianCalendar(); 
			gc.setTime(d1); 
			//统计
			String tjdate = dd.format(gc.getTime());
			System.out.println(tjdate);
			for (Map<String, Object> m : list) {
				Integer id = (Integer) m.get("id");
				String viewurl = (String) m.get("viewurl");
				String submiturl = (String) m.get("submiturl");
				String firstWhere = ""; 
				if(52!=id)
				{
					firstWhere = " and d.isfirst='-1' ";
				}
				//先删除统计日期的数据
				dao.update("delete from t_url_tj where tjdate='"+tjdate+"' and id="+id);
				String tjsql = "insert into t_url_tj "
					    +" select z.sj,	z.id,	a.viewcount,  b.submitcount,	0,	z.sourceid from ("
					    + " select t.id,d.sourceid,'"+tjdate+"' sj from t_url_mark t,t_url_tj_dict d where t.id='"+id+"' "+ firstWhere
					    + " ) z left join "
						+"	(select  '"+id+"' id ,count(1) viewcount,source from t_api_access_log t1 "
						+"	 where t1.url like '"+viewurl+"%' and t1.logdate = '"+tjdate+"' group by  t1.source )a"
						+ " on a.id=z.id and a.source=z.sourceid "
						+"	left join "
						+" (select count(1) submitcount,'"+id+"' id,source  from t_api_access_log t2 where t2.succ='true' and t2.result!='null' and   t2.method='"+submiturl+"' and t2.logdate = '"+tjdate+"' group by  t2.source) b "
						+"	on b.id=z.id and b.source=z.sourceid ";
				
				
				
			   System.out.println(tjsql+";");
			   dao.update(tjsql);
				}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return "完成统计";
	}

    public void process(String date) {
        String access_token = wechatService.getAccessTokenByopenId("gh_b6af115f3e1a");
//        String access_token = "tX7yOPLCu18y3z1v5x9BPi_92Sh2v23oHogNsLAfFitvDXPgpZN-UQNcz_UCjzZr0b88dGCAxz0boWcmAM-wDuZ3erKCu6_VLtF3ktbpwkPHXyKwSIQzah3epvr0CuCmLSEdAEATAM";
        if (!access_token.equals("") && access_token != null) {

            this.deleteUserSummary(date);
            this.deleteUserCumulate(date);
            //保存增量数据
            this.saveUserCumulate(access_token, date, date);
            //保存汇总数据
            this.saveUserSummary(access_token, date, date);
        }
    }

    public void saveUserList() {
        System.out.println("SummaryProcessor任务开始运行");
        String access_token = wechatService.getAccessTokenByopenId("gh_b6af115f3e1a");
        saveUser(access_token, "");
        System.out.println("SummaryProcessor任务结束运行");
    }

    public void saveUser(String access_token, String nextOpenid) {
        Object[] result = WeixinUtil.getUserList(access_token, nextOpenid);
        try {
            if (result != null) {
                String _nextOpenid = (String) result[0];
                List<Object[]> list = (List<Object[]>) result[1];
                if (list.size() > 0) {
                    String sql = " insert into wx_openid_list (openid) values(?)";
                    dao.updateBatch(sql, list);
                }
                saveUser(access_token, _nextOpenid);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveUserSummary(String access_token, String start, String end) {
        String result = WeixinUtil.getUserCountInfo("1", access_token, start, end);
        System.out.println("Summary:" + result);
        if (result != null) {
            try {
                List<Object[]> list = new ArrayList<Object[]>();
                JSONObject jsonObject = JSONObject.parseObject(result);
                JSONArray array = jsonObject.getJSONArray("list");
                for (Object object : array) {
                    Object[] oarray = new Object[2];
                    JSONObject obj = (JSONObject) object;
                    oarray[0] = DateUtil.string2Date(obj.getString("ref_date"), null);
                    oarray[1] = Integer.parseInt(obj.getString("cumulate_user"));
                    list.add(oarray);
                }

                if (list.size() > 0) {
                    String sql = " insert into wx_user_summary (ref_date,cumulate_user) values(?,?)";
                    dao.updateBatch(sql, list);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void deleteUserSummary(String date) {
        try {
            String sql = " delete from wx_user_summary where ref_date = ?";
            dao.update(sql, new Object[]{DateUtil.string2Date(date, null)});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveUserCumulate(String access_token, String start, String end) {
        String result = WeixinUtil.getUserCountInfo("2", access_token, start, end);
        System.out.println("Cumulate:" + result);
        if (result != null) {
            try {
                List<Object[]> list = new ArrayList<Object[]>();
                JSONObject jsonObject = JSONObject.parseObject(result);
                JSONArray array = jsonObject.getJSONArray("list");
                for (Object object : array) {
                    Object[] oarray = new Object[4];
                    JSONObject obj = (JSONObject) object;
                    oarray[0] = DateUtil.string2Date(obj.getString("ref_date"), null);
                    oarray[1] = Integer.parseInt(obj.getString("user_source"));
                    oarray[2] = Integer.parseInt(obj.getString("new_user"));
                    oarray[3] = Integer.parseInt(obj.getString("cancel_user"));
                    list.add(oarray);
                }
                if (list.size() > 0) {
                    String sql = " insert into wx_user_cumulate (ref_date,user_source,new_user,cancel_user) values(?,?,?,?)";
                    dao.updateBatch(sql, list);
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void deleteUserCumulate(String date) {
        try {
            String sql = " delete from wx_user_cumulate where ref_date = ?";
            dao.update(sql, new Object[]{DateUtil.string2Date(date, null)});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
